"""
This module takes objects have been "compiled" previously and returns them as JSON.

TODO(dobromirv): Handle any __iter__ object?
"""

import simplejson
from pythontojavascript.compilers import NotCompiledError

class PythonObjectEncoder(simplejson.JSONEncoder):
  def __init__(self,**kwargs):
    simplejson.JSONEncoder.__init__(self,**kwargs)
    
  def default(self,obj):
    """
    simplejson doesn't handle certain objects - we do that here.
    """
    stringify = ["datetime","timedelta","date","DateTime"]
    if type(obj).__name__ in stringify:
      return str(obj)

    # DO WE REALLY WANT THIS DEFAULT BEHAVIOR?
    #print "iteator:",getattr(obj,"__itr__"
    if hasattr(obj,"__iter__"):
      # We have an iterator. Listify it.
      return list(obj)
      
    # Handle our main case - Compiled Objects - here
    if not hasattr(obj,"_PTJS_serialize"):
      raise NotCompiledError(
            "It looks like the object %s (type: %s) hasn't been compiled." 
             % (obj,type(obj)))
    properties = getattr(obj,"_PTJS_serialize")
    output = {}
    for p in properties:
      output[p] = getattr(obj,p)
    output["_PTJS_ObjectName"] = obj.__class__.__name__
    # This prevents PythonObject from thinking that we're creating an object
    output["_PTJS_FromServer"] = True
    return output

def encode(objects):
  return "(" + simplejson.dumps(objects,cls=PythonObjectEncoder) + ")"
